/*
  Programa Wifis, 2010-2011
  Autor: Nilhcraiv

This file is part of Wifis.

    Wifis is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Wifis is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Wifis.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QModelIndex>
#include <QIcon>
#include <QDesktopServices>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "linuxos.h"
#include "aboutdialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), classSave(0), model(0), OS(0), dialog(0), opciones(0), timer(0),
    ui(new Ui::MainWindow), version(0.13), showMaximizedWindow(false), inicio(true)
{
    ui->setupUi(this);
    setWindowTitle("Wifis");
    this->show();
    QWidget::setWindowIcon(QIcon(":/pics/icono.png"));

    this->ui->connectButton->setIcon(QIcon(":/pics/conectar.png"));
    this->ui->startButton->setIcon(QIcon(":/pics/actualizar.png"));

    this->display = new displayInformation(&this->vectorNetWorks);
    this->classSave = new save(this);
    this->opciones = new options(this,this->classSave,&config);
    this->dialogo = new Dialogo(this);
    this->updates = new updatesThread(this,&version,&inicio);
    this->dialog = new QProgressDialog("Detectando redes...",0,0,0,this);//El cero elimina el boton cancel.
    this->timer = new QTimer(this);

    this->config = this->classSave->readConfiguration();
    this->ui->treeView->setSortingEnabled(true);

#if defined (__WIN32__)
    OS = new windowsos(this);
#endif

#if defined(__linux__)
    OS = new linuxos(this);
#endif

#if defined( __APPLE_CC__)
    //Class for apple OS
#endif

    connect(OS,SIGNAL(finished()),dialog,SLOT(accept()));//para que se cierre el dialogo modal

    dialog->setWindowFlags(Qt::Tool | Qt::WindowTitleHint | Qt::CustomizeWindowHint);//para quitar los botones de la barra de titulo

    connect(updates,SIGNAL(blockSignalsQTimer(bool)),this,SLOT(blockSignalsQTimer(bool)));
    connect(updates,SIGNAL(showDialog(bool)),dialogo,SLOT(showDialog(bool)));
    connect(updates,SIGNAL(setTextCaptionDialog(QString)),dialogo,SLOT(setWindowCaption(QString)));
    connect(updates,SIGNAL(setTextCancelDialog(QString)),dialogo,SLOT(setCancelText(QString)));
    connect(updates,SIGNAL(setTextDialog(QString)),dialogo,SLOT(setShowText(QString)));
    connect(updates,SIGNAL(addButtonDialog(QString,QDialogButtonBox::ButtonRole)),
            dialogo,SLOT(addButton(QString,QDialogButtonBox::ButtonRole)));
    connect(updates,SIGNAL(removeButtonDialogUpdate()),dialogo,SLOT(removeButtonUpdate()));
    connect(updates,SIGNAL(closeProgressDialog()),dialog,SLOT(hide()));
    connect(dialogo,SIGNAL(blockSignalsQTimer(bool)),this,SLOT(blockSignalsQTimer(bool)));
    connect(dialogo,SIGNAL(accepted()),updates,SLOT(checkLinkdownloadNewVersion()));//Boton aceptar añadido si hay una actualización.
    connect(ui->startButton,SIGNAL(clicked()),SLOT(detectNetworks()));
    connect(ui->actionSalir,SIGNAL(triggered()),SLOT(close()));
    connect(ui->actionAcerca_de,SIGNAL(triggered()),SLOT(acercaDe()));
    connect(ui->actionActualizaciones,SIGNAL(triggered()),this,SLOT(slotCheckUpdates()));
    connect(ui->actionOpciones,SIGNAL(triggered()),this,SLOT(slotOptions()));
    connect(ui->actionAyuda,SIGNAL(triggered()),this,SLOT(slotAyuda()));
    connect(ui->connectButton,SIGNAL(clicked()),SLOT(slotConectarButton()));
    connect(ui->actionGuardar_redes,SIGNAL(triggered()),this,SLOT(saveNetworks()));
    connect(timer, SIGNAL(timeout()), this, SLOT(detectNetworks()));

    if(config.isEmpty())
    {
        slotCheckUpdates();
        detectNetworks();
        timer->start(120000);//2 minutes
    }
    else
    {
        if(config.at(0)==0){//comprobar actualizaciones al inicio
            this->opciones->setChecked_1(false); inicio=false;}//Inicio es false para que el usuario manualmente pueda ver toda la infrmacion acerca de las actualizaciones.
        else{
            this->opciones->setChecked_1(true); slotCheckUpdates();}
        if(config.at(1)==0){//Iniciar maximizado
            this->opciones->setChecked_2(false); this->showMaximizedWindow=false;}
        else{
            this->opciones->setChecked_2(true); this->showMaximizedWindow=true;}
        if(config.at(2)==0){//Enviar estadisticas anonimas
            this->opciones->setChecked_3(false);}
        else{
            this->opciones->setChecked_3(true);}
        if(config.at(3)==0){//Detectar redes al iniciar la aplicacion
            this->opciones->setChecked_4(false);}
        else{
            this->opciones->setChecked_4(true); detectNetworks();}
        if(config.at(4)==0){//Modo monitor
            this->opciones->setChecked_5(false);}
        else{
            this->opciones->setChecked_5(true);}

        this->opciones->setValueDoubleSpinBox(config.at(5));//Tiempo de actualizacion de redes
        timer->start(config.at(5));
    }
}//Constructor

MainWindow::~MainWindow()
{
    delete ui;
    delete dialog;
    delete classSave;
    delete display;
    delete dialogo;
    delete OS;
}//dConstructor

//Private slots

void MainWindow::slotConectarButton()
{
    if(this->model == 0)
        return;
    int check=0,selected;

    for(int i =0;i<this->model->rowCount();i++)
    {
        if(this->display->isCheck(i,this->model)){
            check++; selected=i;}
    }
    if(check==0){
        QMessageBox::information(this,"Información","¡Selecciona una red!","Aceptar"); return;}
    if(check>1){
        QMessageBox::information(this,"Información","¡Selecciona solo una red!","Aceptar"); return;}

    if(!this->model->item(selected,9)->text().trimmed().startsWith("Desconocida"))//Si no empieza por desconocida, significa que hay password.
    {
#if defined (__WIN32__)
    this->OS->connectToNetwork(this->model->item(selected,0)->text().trimmed(),this->model->item(selected,9)->text().trimmed());
    QMessageBox::information(this,"Conectar","Se ha añadido la red a las conexiones inalámbricas de Windows, si es posible se realizará la conexión.","Aceptar");
#endif
    }//if
    else
    {
        QMessageBox::information(this,"Imposible conectar","Red no vulnerable o contraseña no disponible en esta versión de Wifis.\n"
                                 "Quizás este disponible en próximas versiones.","Aceptar");
    }
}//slotConectarButton

void MainWindow::detectNetworks()
{
    this->timer->blockSignals(true);
    dialog->setLabelText("Detectando redes...");

#if defined (__WIN32__)
    OS->start();
    dialog->exec();

    this->vectorNetWorks = this->OS->vectorNetworks;
    this->model = this->display->getModel();
    this->ui->treeView->setModel(this->model);

    if(this->model->rowCount()>0)
    {
        this->ui->connectButton->setEnabled(true);
    }
    else
    {
        this->ui->connectButton->setEnabled(false);
        QMessageBox::information(this,"Sin redes","No se han detectado redes inalámbricas, esto puede ser debido a:\n\n"
                                 " * Tarjeta de red no disponible.\n * No hay redes inalámbricas disponibles.\n * Error interno(Cuando "
                                 "este error se solucione, wifis mostrara las redes).\n" " * Sistema operativo no soportado."
                                 ,"Aceptar");
        return;
    }

    for(int i=0;i<8;i++)//Ajusto el contenido al arbol.
        this->ui->treeView->resizeColumnToContents(i);

    this->timer->blockSignals(false);//Vuelvo a activar la detección automática.

    return;
#elif defined(__linux__)
    QMessageBox::information(this,"Información","GNU/Linux todavía no implementado","Aceptar");
    this->timer->blockSignals(false);//Vuelvo a activar la detección automática.
#else
    QMessageBox::information(this,"Información","Sistema operativo todavía no implementado","Aceptar");
    this->timer->blockSignals(false);//Vuelvo a activar la detección automática.
#endif
}//detecNetworks

void MainWindow::acercaDe()
{
    aboutDialog acerca(this);
    acerca.exec();//dialogo modal
}//acercaDe

void MainWindow::slotCheckUpdates()
{
    timer->blockSignals(true);
    dialog->setLabelText("Comprobando actualizaciones...");
    updates->ejecutar();
    dialog->exec();
    inicio = false;
}//updates

void MainWindow::blockSignalsQTimer(bool block)
{
    this->timer->blockSignals(block);
}//blockSignalsQTimer

void MainWindow::saveNetworks()
{
    classSave->guardarRedes(this->vectorNetWorks);
}//saveNetworks

void MainWindow::slotOptions()
{
    opciones->exec();
}//slotOptions

bool MainWindow::maximized()
{
    return showMaximizedWindow;
}//maximized

void MainWindow::slotAyuda()
{
    if(!QDesktopServices::openUrl(QUrl("http://code.google.com/p/wifis/w/list", QUrl::TolerantMode)))
        QMessageBox::warning(this,"Error","Ha sido imposible abrir el navegador web.");
}//slotAyuda

void MainWindow::slotSort(int d)
{
    qDebug() << d;
}
